
/****************************************************************

8080disasm,the 8080 cpu disassembeler by Elizeu Carlos aka wrproject
@Authors: Elizeu Carlos
contact: mixeliseu13_8@hotmail.com  elizeucc@gmail.com
*******************************************************************/

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include "functions.h"
#include "constants.h"
using namespace std;
//this function converts a hex number to an equivalent int
int hex_to_int(string hex)
{
    char c='a';
    int total=0,temp=0;
    int high_order=hex.length()-1; //this variable stores the high order of a bit
    
    
    for(int i=0;i<hex.length();i++)
    {
            c=(char)tolower(hex[i]); //this line obtain the correspondent numebr or letter
            if(c>='a' && c<='f')
            {
                
                temp=((c-'a')+10)*((int)pow(16.0,high_order));
                total+=temp;
                
                high_order--;
                
            }
            else if(c>='0' && c<='9')
            {
                
                temp=(c-'0')*(int)pow(16.0,high_order);
                total+=temp;
                high_order--;
            }
            else
            {
                total=-1;
            }
            
    }
    
    return total;
}



//this function will load the current program in memoryss
int* load_to_memory(char* file)
{
     
int* temp_memory=NULL;//memroia de 65Kbytes

int size=0;
int i=0;
char byte;
ifstream f(file,ios::binary);
int c=0;


if(f.is_open())
{
f.seekg(0,ios::end);
size=f.tellg();
f.seekg(0,ios::beg);
temp_memory=new int[size];
while ((c=(int)f.get()) != -1)
{
temp_memory[i++]=c;
//cout<<c<<endl;
//cout<<byte<<endl;
}

}
else
{
   cout<<"An error ocurred while attempting to open the file"; 
}


f.close();
return temp_memory;
}



//this function obtains the file size
int getFileSize(char* file)
{
    int size=0; //the size in bytes
    ifstream f(file);
    
    if(f.is_open())
    {
               f.seekg(0,ios::end);    
               size=f.tellg();
               f.seekg(0,ios::end);
               return size;
    }
    
    
    return -1;
    
}



bool file_exists(char* file)
{
bool ret=true;

ifstream f(file);

if(!f.is_open())
{
    ret=false;
    f.close();
}

f.close();

return ret;
     
     
}

void show_header_text()
{
     
cout<<"::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"<<endl;
cout<<"::        8080DISASM, the 8080 cpu disassembler           ::"<<endl;
cout<<"::                                                        ::"<<endl;
cout<<"::                     By Elizeu Carlos                   ::"<<endl;
cout<<"::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"<<endl;
cout<<"\n\n";
}
